/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.eschool.dao;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import com.eschool.model.Alert;
import com.eschool.model.Branch;
import com.eschool.model.Permission;
import com.eschool.model.Role;
import com.eschool.model.SaasAdmin;
import com.eschool.model.School;
import com.eschool.util.HibernateUtil;
import com.eschool.util.JdbcUtil;

/**
 *
 * @author Ammar
 */

public class BranchDao{
	
	
	public static int addBranch(Branch branch) {
    	int branchId = -1;
    	
    	Connection connection = JdbcUtil.openConnection();
		try{
			CallableStatement storedProc = connection.prepareCall("{ call InsertBranch(?,?,?,?,?,?,?) }");
			storedProc.setString(1, branch.getBranchTitle());
			storedProc.setString(2, branch.getPhoneNumber());
			storedProc.setString(3, branch.getFaxNumber());
			storedProc.setString(4, branch.getAddress());
			storedProc.setString(5, branch.getPrincipalName());
			storedProc.setInt(6, branch.getSchool().getSchoolId());
			storedProc.registerOutParameter(7, java.sql.Types.INTEGER);
			storedProc.execute();
		
			branchId = storedProc.getInt(7);
			connection.close();
		}
		
		catch(Exception e){
			branchId = -1;
			connection.close();
			e.printStackTrace();
		}
		finally{
			return branchId;
		}
		
	}
	
	public static Branch getBranchByProperty(String property, Object value) {
		
		Session session = HibernateUtil.currentSession();
	      
		Criteria crit = session.createCriteria(Branch.class);
		crit.add(Restrictions.eq(property, value));
		
		Branch branch= (Branch) crit.uniqueResult();
		
        HibernateUtil.closeSession(session);

        return branch;
	}
	
	public static List getBranches(Map<String , Object> conditions) {
		
		Session session = HibernateUtil.currentSession();
		Criteria crit = session.createCriteria(Branch.class);

		if (conditions != null)
			for (Iterator iterator = conditions.entrySet().iterator(); iterator.hasNext();) {
			
				Map.Entry condition = (Map.Entry) iterator.next();
				
				crit.add(Restrictions.eq(((String) condition.getKey()), condition.getValue()));
			}
		
		List branches = (List<Branch>) crit.list();
		
        HibernateUtil.closeSession(session);

        if(branches == null)
        	return Collections.EMPTY_LIST;
        
        return branches;
	}
	
/*
	
	public static List<Saasschool> getAllSaasschool() {
		Session session = HibernateUtil.currentSession();
	      
		Criteria crit = session.createCriteria(Saasschool.class);
		
		List schools = crit.list();
		
        HibernateUtil.closeSession(session);
        return schools;
	}*/
}
